<?php
namespace Frieza\Modules\Decoration\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\model\Decoration\Tag as mTag;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\service\es\EsDecorateTopic;
use Doraemon\cache\DecorateThemeCount;
use Doraemon\service\Decoration\Main as sMain;
use Doraemon\tools\ImgUrl;
use Doraemon\service\Decoration\FormatSubject;
use Doraemon\service\Photos;

class MainSubjectController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
        Admin::script($this->setScript());

    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;

        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }

            }
        }
        if($params['name']) {
            $where['name']  =$params['name'];
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }
        $data['ORDER'] = ['id' => 'DESC'];

        return $data;
    }


    public function listAction($request = []){
        $data = [
            'list'=> [],
            'total' => 0,
        ];
        if($request['AND']['id'] > 0){
            $sql = 'select id,sid from `hhz_decoration_adv` where FIND_IN_SET('.$request['AND']['id'].',rela_id) and show_type = '.mAdv::SHOW_TYPE_1;
            $advId = mAdv::query($sql)->fetchAll();
            if(!empty($advId)){
                $sid =  array_column($advId, 'sid');
                if(isset($request['AND']['name'])) {
                    $data = sMain::getSubject(['id' => $sid, 'name[~]'=>$request['AND']['name']]);
                }else{
                    $data = sMain::getSubject(['id' => $sid]);
                }
            }
        }else{
            $data = mSubject::getAllByWhere($request);
        }

        $gridModel = new pGridDataModel($data, count($data), [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($request) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '主题名称')->placeholder('请输入主题名称');
                });
            });

            $grid->tools(function (Grid\Tools $tool)use($request) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '主题位排序', '',
                    '/admin/decoration/subject/sorts/'.$request['AND']['parent_id'].'/'.$request['AND']['id']));
            });

            $grid->column('id', 'id');
            $grid->column('name', '主题名称');
            $grid->column('color', '背景颜色')->display(function(){
                return '<p style="background-color: '.$this->color.';color:'.$this->color.';width: 50px; display: block">颜色</p>';
            });
            $grid->column('rela_tag', '关联tag');
            $grid->column('rela_wiki', '关联wiki分类');
            $grid->column('search_tag', '搜索描述');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

        });

        $list = $listGrid->render();

        return $list;
    }

    public function edit(Request $request,Content $content, $parentId = 0, $sonId = 0, $sid = 0){
        $requests = $request->all();
        $requests['parent_id'] = $parentId;
        $requests['id'] = $sonId;
        $requests['sid'] = $sid;
        $requests = self::_filterWhere($requests);

        if($parentId > 0){
            $request['parent_id'] = $parentId;
            $preUrl = '/decoration/category/'.$parentId.'/edit';
        }
        if($sonId > 0){
            $request['id'] = $sonId;
            $preUrl = $preUrl. '/' .$sonId.'/edit';
        }

        $tab = new Tab();
        $tab->add('基本信息', self::editAction(
            $requests,
            strpos($request->url(), 'create'),
            '/admin'.$preUrl.'/subject/'.$sid.'/save')
        );
        if(!strpos($request->url(), 'create')) {
            $tab->addLink('资源位列表', '/admin/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/subject/'.$sid.'/adv');
        }

        if(!empty($preUrl)){
            $preUrls = ['text' => '上级分类', 'url' => $preUrl];
        }

        return $content
            ->header('分类编辑')
            ->breadcrumb(
                $preUrls,
                ['text' => '主题列表', 'url' => $preUrl.'/subject'],
                ['text' => '编辑主题', 'url' => '/decoration/category/create']
            )
            ->body($tab);
    }

    public function editAction($request, $isCreate = false, $preUrl = ''){
        $data = [];
        if(!$isCreate) {
            if (!empty($request['AND']['sid'])) {
                $data = mSubject::getOneByWhere(['id' => $request['AND']['sid']]);
            }
        }

        $form = new Form($data);

        if(isset($request['AND']['sid'])){
            $form->hidden('id');
        }

        $form->text('name', '主题名称')->setWidth(4, 2)->required('不能为空');
        $form->color('color', '主题背景色')->setWidth(4, 2)->required('不能为空');
        $form->text('rela_tag', '关联tag');
        $form->multipleSelect('rela_wiki', '关联wiki分类')->options(Category::getCategorysByDeep([1,2,3]));
//        $form->checkbox('rela_wiki2', '关联wiki分类') ->options($wiki_category);
        $form->text('search_tag', '搜索描述')->setWidth(4, 2);

        $form->action($preUrl);

        return $form->render();
    }

    public static function save(Request $request)
    {
        $params = $request->all();
        if(!empty($params['rela_wiki'])){
            $params['rela_wiki'] = implode(',', array_filter($params['rela_wiki']));
        }

        $param = [
            'name'=> $params['name'],
            'color'=> $params['color'],
            'rela_tag'=> $params['rela_tag'],
            'rela_wiki'=> $params['rela_wiki'],
            'search_tag'=> $params['search_tag'],
            'admin_id'=>Admin::user()->id,
        ];
        if(!empty($params['obj_id'])){
            $param['obj_id'] = $params['obj_id'];
        }

        if(!isset($params['id']) || $params['id'] == '') {
            $param['add_time'] = date('Y-m-d H:i:s',time());
            $result = mSubject::addData($param);
            $param['id'] = $result;
        }else{
            $param['edit_time'] = date("Y-m-d H:i:s" , time());
            $result = mSubject::updateData($param,['id'=>$params['id']]);
            $param['id'] = $params['id'];
        }

        if($result){
            sCache::updateCache();

            //更新搜索的缓存信息
            \Doraemon\cache\Queue::insertQueue('queue/decoratetopic/save', array(
                'id' => $param['id'],
            ), \Doraemon\cache\Queue::QUEUE_DORAEMON);

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/decoration/mainsubject/create/'.$param['id'])->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => $result
            ]);

            return back()->with(compact('error'));
        }

    }

//    public static function del($id,  $parentId = 0, $sonId = 0, $sid = 0)
//    {
//        //如果关联了关键词或者广告位，提示不能删除
//        //$sql = 'select id from `hhz_decoration_tag` where FIND_IN_SET('.$sid.',sid)';
//        //$rela_tag = mTag::query($sql)->fetchAll();
//        $rela_adv = mAdv::getAllByWhere(['sid'=>$sid],'id');
//        if(!empty($rela_adv)){
//            return response()->json([
//                'status' => false,
//                'message' => "已关联关键词或者广告位，不能删除，请先解除关联",
//            ]);
//        }
//
//
//        $data = ['status'=>mSubject::STATUS_DELETE];
//        $result = mSubject::updateData($data, ['id'=>$sid]);
//
//        if($result){
//            sCache::updateCache();
//
//            return response()->json([
//                'status' => true,
//                'message' => "操作成功",
//            ]);
//        }else{
//            return response()->json([
//                'status' => false,
//                'message' => "操作失败",
//            ]);
//        }
 //  }

    public  function delsubject(Request $request,Content $content , $id = 0)
    {
        $rela_adv = mAdv::getAllByWhere(['sid'=>$id ,'show_type' => mAdv::SHOW_TYPE_1 ,'status'=> mAdv::STATUS_OPEN],'id');
        if(!empty($rela_adv)){
            return response()->json([
                'status' => false,
                'message' => "已关联关键词或者广告位，不能删除，请先解除关联",
            ]);
        }


        $data = [
            'status'=>mSubject::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
            'edit_time' => date("Y-m-d H:i:s" , time())
        ];
        $result = mSubject::updateData($data, ['id'=>$id]);

        if($result){
            sCache::updateCache();
            //删除搜索主题的缓存
            \Doraemon\cache\Queue::insertQueue('queue/decoratetopic/delete', array(
                'id' => $id,
            ), \Doraemon\cache\Queue::QUEUE_DORAEMON);
            return response()->json([
                'code' => 1,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }


    public function index(Request $request,Content $content){

        $request = $request->all();
        $condition = self::_filterWhere($request);

        $tab = new Tab();
        $tab->add('主题列表', self::listGrid( $request,$condition));
        if(!empty($preUrl)) {
            return $content
                ->header('主题列表')
                ->breadcrumb(
                    $preUrl
                )
                ->body($tab);
        }else{
            return $content
                ->header('主题列表')
                ->breadcrumb(
                    ['text' => '主题列表', 'url' => '/decoration/subject/create']
                )
                ->body($tab);
        }
    }

    public function  listGrid($request = [] , $condition){
      $condition['AND']['status'] = mSubject::STATUS_OPEN;
        $subject = mSubject::getAllByWhere($condition);
        unset($condition['LIMIT']);
        $total = mSubject::getCount($condition);

        if($subject && is_array($subject)){
            $obj_ids = array_unique(array_filter(array_column($subject , 'obj_id'))) ? : [];
            $photos_list = [];
            if($obj_ids && is_array($obj_ids)){
                $photos_list = Photos::getPhotos($obj_ids);
            }
            foreach($subject as &$value){
                 if($value['rela_wiki']){
                     $value['rela_wiki'] = sMain::getWikiCategoryByid($value['rela_wiki'], true);
                     $value['wiki_info'] = array_filter(explode(",",$value['rela_wiki']));
                 }
                if($value['rela_tag']){
                    $value['tag_info'] = array_filter(explode(",",$value['rela_tag']));
                }
                if($photos_list[$value['obj_id']]){
                    $value['cover_img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP,$photos_list[$value['obj_id']]['pic_org_id'], ImgUrl::IMAGE_SIZE_A_PIC);
                }
            }
        }
        $gridModel = new pGridDataModel($subject, $total, [
            'perPage' => $request['per_page'] ? : self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            //$grid->disableFilter();
           // $grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            //$grid->expandFilter();
          //  $grid->disableActions();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '主题名称')->placeholder('请输入主题名称');
                });
            });
            $grid->tools(function (Grid\Tools $tool) {
                $tool->append('<div class="pull-right"><div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
    <a href="/admin/decoration/mainsubject/create" class="btn btn-sm btn-success" title="新增">
        <i class="fa fa-plus"></i><span class="hidden-xs">&nbsp;&nbsp;新增</span>
    </a>
</div></div>');
            });

            $grid->column('id', 'id');
            $grid->column('name', '主题名称');
            $grid->column('color', '背景颜色')->display(function(){
                return '<p style="background-color: '.$this->color.';color:'.$this->color.';width: 50px; display: block">颜色</p>';
            });

            $grid->column('cover_img_url', '封面')->display(function(){
                if(!empty($this->cover_img_url)) {
                    return '<img style="width:150px;height:100px" src="' . $this->cover_img_url . '" >';
                }
            });

            $grid->column('rela_tag', '关联tag')->display(function() {
                $options='';
                if ($this->tag_info) {
                    foreach ($this->tag_info as $tag) {
                        $options = $options . '<button style="display:inline-block;margin:2px;" class="marktag btn btn-sm btn-primary" data-had="">'.$tag.'</button>';
                    }
                }
                return $options;
            })->style("width:200px");


            $grid->column('rela_wiki', '关联wiki分类')->display(function() {
                $options='';
                if ($this->wiki_info) {
                    foreach ($this->wiki_info as $wiki) {
                        $options = $options . "<button style='display:inline-block;margin:2px;' class='marktag btn btn-sm '   >$wiki</button>&nbsp;";
                    }
                }
                return $options;
            }) -> style("width:200px");
            $grid->actions(function (Grid\Displayers\Actions $actions){
                //  $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa fa-edit"  href="/admin/decoration/mainsubject/create/'.$actions->row->id.'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-trash	delsubject" data-id="' . $actions->row->id . '"  href="javascript:void(0);">删除</a>');
                $actions->append('&nbsp;&nbsp;<a class="fa fa-info-circle"  href="/admin/decoration/mainadv/taglist/'.$actions->row->id.'">查看主题详情页</a>');
            });

//            $grid->column('adv', '操作')->display(function(){
//                $action = '';
//
//
////                $action .='<a class="fa fa-info-circle" href="/admin/decoration/subject/'.$this->id.'/adv">查看轮播baner</a><br/>';
////                $action .='<a class="fa fa-info-circle" href="/admin/decoration/mainadv/subjectlist/'.$this->id.'">查看内容卡片</a><br/>';
////                $action .='<a class="fa fa-info-circle" href="/admin/decoration/mainadv/taglist/'.$this->id.'">查看标签</a><br/>';
//                return $action;
//            });


        });

        $list = $listGrid->render();

        return $list;
    }

    public function create(Request $request ,Content $content ,$id = 0 ){

        if(!empty($id)){
            $data = mSubject::getOneByWhere(['id'=>$id]);
        }else{
            $data = [];
        }
        $form = new Form($data);

        $form->hidden('id');
        $form->text('name', '主题名称')->setWidth(4, 2)->required('不能为空');
        $form->color('color', '主题背景色')->setWidth(4, 2)->required('不能为空');
        $form->text('rela_tag', '关联tag')->help("填写tag 以','分割");
        $form->multipleSelect('rela_wiki', '关联wiki分类')->options(Category::getCategorysByDeep([1,2,3]));
        $form->text("obj_id" , '图片id');
//        $form->checkbox('rela_wiki2', '关联wiki分类') ->options($wiki_category);
        $form->text('search_tag', '搜索描述')->setWidth(4, 2);

        $form->action('/admin/decoration/mainsubject/save');
        $content->breadcrumb(
            ['text' => '主题列表', 'url' => '/decoration/mainsubject'],
            ['text' => '新增', 'url' => '/decoration/mainsubject/create']

        );

        return $content->body($form->render());
    }

    public function sort(Request $request){
        $params = $request->all();

        $result = mAdv::action(function()use($params){
            foreach($params['sort'] as $_k=>&$_v){
                if(!mAdv::updateData(['sort' => $_v], ['id' => $_k])){
                    return false;
                }
            }
            return true;
        });

        if($result){
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sorts(Request $request,Content $content, $parentId = 0, $sonId = 0){
        return $content
            ->header('主题排序')
            ->breadcrumb(
                ['text' => '上级分类', 'url' => '/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/subject'],
                ['text' => '主题排序']
            )
            ->body(self::sortList($sonId));
    }

    public function sortList($sonId){
        $subject = mSubject::getAllByWhere(['status'=>1], ['id','name']);
        $subject = array_column($subject, 'name', 'id');

        $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$sonId.',rela_id) and show_type = '.mAdv::SHOW_TYPE_1.' order by sort ASC';
        $data['list'] = mAdv::query($sql)->fetchAll();
        $data['list'] = array_map(function($_item)use($subject){
            $_item['subject'] = $subject[$_item['sid']];
            return $_item;
        }, $data['list']);
        $data['total'] = count($data['list']);
        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();

            $grid->tools(function (Grid\Tools $tool) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '主题位排序', '', '/admin/decoration/subject/sort'));
            });

            $grid->column('id', 'id')->sort();
            $grid->column('subject', '主题名称');
            $grid->column('sort', '权重');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

        });

        $list = $listGrid->render();

        return $list;
    }

    private function setScript()
    {
        return <<<SCRIPT
       
        $('.delsubject').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要删除么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/decoration/mainsubject/del/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        })
        
        $('.lock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要锁定「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/lockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        });
SCRIPT;
    }


}